//------------------------------------------------------------------------------
#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QDesktopWidget>
#include <QDebug>
#include <QPainter>
#include <QDateTime>
//------------------------------------------------------------------------------
// Constructor/Destructor
//------------------------------------------------------------------------------
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow){
	ui->setupUi(this);

	m_aboutDialog = 0;

	m_customIconFile = "" /*"/usr/share/pixmaps/apple-red.png"*/ ;
	m_unreadNotifications = 0;

	m_trayMenu = new QMenu();
	m_quitAction = m_trayMenu->addAction(tr("Quit"));

	m_trayIcon = new QSystemTrayIcon(this);
	updateIconPix();
	m_trayIcon->setToolTip(this->windowTitle());
	m_trayIcon->setContextMenu(m_trayMenu);
	m_trayIcon->show();

	// Window geometry
	const QDesktopWidget *desktop = QApplication::desktop();
	QRect screenRect = desktop->screenGeometry(desktop->primaryScreen());
	const QRect &thisRect = geometry();
	this->setGeometry(QRect((screenRect.width()-thisRect.width())/2,(screenRect.height()-thisRect.height())/2,thisRect.width(),thisRect.height()));

	m_notificationsModel = new QStandardItemModel(this);
	m_notificationsModel->setColumnCount(3);
	m_notificationsModel->setSortRole(Qt::DisplayRole);

	QStringList notifHeaderLabels;
	notifHeaderLabels << tr("Date") << tr("Title") << tr("Description");
	m_notificationsModel->setHorizontalHeaderLabels(notifHeaderLabels);

	ui->m_notificationsHistoryTable->setModel(m_notificationsModel);
	ui->m_notificationsHistoryTable->sortByColumn(0, Qt::AscendingOrder);
	ui->m_notificationsHistoryTable->horizontalHeader()->setResizeMode(QHeaderView::ResizeToContents);
	ui->m_notificationsHistoryTable->horizontalHeader()->setResizeMode(2, QHeaderView::Stretch);	// Stretch on description column

	// Signals/Slots connections
	connect(ui->m_actionQuitter, SIGNAL(triggered()), this, SIGNAL(quitRequested()));
	connect(m_trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(iconActivated(QSystemTrayIcon::ActivationReason)));
	connect(m_quitAction, SIGNAL(triggered()), this, SIGNAL(quitRequested()));
}
//------------------------------------------------------------------------------
MainWindow::~MainWindow(){
	delete m_trayIcon;

	if(m_aboutDialog)
		delete m_aboutDialog;

	if(m_notificationsModel)
		delete m_notificationsModel;

	delete ui;
}
//------------------------------------------------------------------------------
// Public slots
//------------------------------------------------------------------------------
void MainWindow::displayMessage(STNMessage msg){
	QList<QStandardItem*> row;

	QString now = QDateTime::currentDateTime().toString(Qt::SystemLocaleShortDate);

	QStandardItem* dateItem			= new QStandardItem(now);
	QStandardItem* titleItem		= new QStandardItem(msg.getTitle());
	QStandardItem* messageItem		= new QStandardItem(msg.getMessage());

	row << dateItem << titleItem << messageItem;

	m_notificationsModel->appendRow(row);

	m_unreadNotifications++;
	updateIconPix();

	if(m_trayIcon->isVisible())
		m_trayIcon->showMessage(msg.getTitle(), msg.getMessage(), QSystemTrayIcon::NoIcon, 5000);
}
//------------------------------------------------------------------------------
// Protected methods
//------------------------------------------------------------------------------
void MainWindow::closeEvent(QCloseEvent *evt){
	hide();
	evt->ignore();
}
//------------------------------------------------------------------------------
// Private slots
//------------------------------------------------------------------------------
void MainWindow::iconActivated(QSystemTrayIcon::ActivationReason reason){
	switch (reason) {
		case QSystemTrayIcon::Trigger:
		case QSystemTrayIcon::DoubleClick:
			if(isVisible())
				hide();
			else
				show();
		break;

		default:
			//qDebug()<<"MainWindow::iconActivated("<<reason<<")";
		break;
	}
}
//------------------------------------------------------------------------------
void MainWindow::on_m_clearButton_released(){
	m_notificationsModel->setRowCount(0);

	m_unreadNotifications = 0;
	updateIconPix();
}
//------------------------------------------------------------------------------
void MainWindow::on_m_actionAbout_triggered(){
	if(!m_aboutDialog)
		m_aboutDialog = new AboutDialog(this);

	m_aboutDialog->show();
}
//------------------------------------------------------------------------------
// Private methods
//------------------------------------------------------------------------------
void MainWindow::updateIconPix(){
	QPixmap pix;

	// Draw default icon
	if(m_customIconFile.isEmpty() || !QFile(m_customIconFile).exists()){
		pix = QPixmap(DEFAULT_ICON_SIZE);
		QPainter p(&pix);
		p.fillRect(pix.rect(),DEFAULT_ICON_BACKGROUND_COLOR);
	}
	// Draw user custom icon
	else{
		pix = QPixmap(m_customIconFile);
	}

	// Draw unread notifications number
	if(m_unreadNotifications > 0){
		QString text = tr("%1").arg(m_unreadNotifications);
		QPainter p(&pix);

		QFont font = DEFAULT_ICON_FONT;
		font.setPixelSize(pix.height()*FONT_HEIGHT_FACTOR);
		font.setStyleStrategy(QFont::NoAntialias);

		QRect bnd = QFontMetrics(font).boundingRect(text);

		// Text reduction
		while(
			(bnd.width() > pix.width()-2 || bnd.height() > pix.height()-2) &&
			font.pointSize() > 1
		){
			font.setPointSize(font.pointSize()-1);
			bnd = QFontMetrics(font).boundingRect(text);
		}

		p.setPen(DEFAULT_ICON_TEXT_COLOR);
		p.setFont(font);
		p.drawText(pix.rect(), Qt::AlignCenter, text);
	}

	m_trayIcon->setIcon(QIcon(pix));
}
//------------------------------------------------------------------------------
